package com.breaks.adww;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.FileCopyUtils;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Set;
import java.util.stream.Collectors;

@Component
public class CopyFileTask {

    private final static Logger logger = LoggerFactory.getLogger(CopyFileTask.class);

    @Resource
    private TaskConfig taskConfig;

    final String oldDirMark = ".old";
    final String currentDirName = "current";
    final String fileSuffix = ".png";

    @Scheduled(initialDelay = 10000, fixedDelay = 1000*60*60)
    public void task() {

        String destFileDir = taskConfig.getDestFileDir();
        String sourceFileDir = taskConfig.getSourceFileDir();
        int segmentSize = taskConfig.getSegmentSize();
        int[][] imagePixelSizeFilterArray = taskConfig.getImagePixelSizeFilterArray();

        File destFileDirF = new File(destFileDir);
        if (!destFileDirF.exists()) {
            destFileDirF.mkdirs();
            if (!destFileDirF.exists()) {
                return;
            }
        }

        File sourceFileDirF = new File(sourceFileDir);
        if (!sourceFileDirF.exists()) {
            logger.error("sourceFileDir对应目录不存在{}", sourceFileDir);
            return;
        }
        File[] sourceFiles = sourceFileDirF.listFiles();
        // 过滤源文件，去掉不满足拷贝要求的源文件
        Set<String> sourceFileSet = Arrays.stream(sourceFiles)
                .filter(file -> filterSourceFile(imagePixelSizeFilterArray, file))
                .map(File::getName).collect(Collectors.toSet());

        File[] destFileDirFs = destFileDirF.listFiles(file -> file.isDirectory() && !file.getName().endsWith(oldDirMark));
        File currentFileDirF = new File(destFileDir + File.separator + currentDirName);
        if (!currentFileDirF.exists()) {
            currentFileDirF.mkdirs();
        }

        // 过滤源文件，去掉已拷贝的源文件
        for (File file : destFileDirFs) {
            File[] picFiles = file.listFiles();
            boolean repeat = false;
            for (File picFile : picFiles) {
                String filename = picFile.getName().replace(fileSuffix, "");
                if (sourceFileSet.contains(filename)) {
                    sourceFileSet.remove(filename);
                    repeat = true;
                }
            }
            // 将历史目录加上old标志
            if (!currentDirName.equals(file.getName())) {
                if (!repeat) {
                    file.renameTo(new File(file.getAbsolutePath() + oldDirMark));
                }
            }
        }

        try {
            // 拷贝文件
            String destFileDirPath = destFileDir + File.separator + currentDirName + File.separator;
            for (String s : sourceFileSet) {
                FileCopyUtils.copy(new File(sourceFileDir + File.separator + s),
                        new File(destFileDirPath + s + fileSuffix));
            }
            // 将当前目录置为历史目录
            if (currentFileDirF.list().length >= segmentSize) {
                currentFileDirF.renameTo(new File(destFileDir + File.separator + System.currentTimeMillis()));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public boolean filterSourceFile(int[][] imagePixelSizeFilterArray, File file) {
        try {
            BufferedImage bufferedImage = ImageIO.read(file);
            int height = bufferedImage.getHeight();
            int width = bufferedImage.getWidth();
            if (imagePixelSizeFilterArray != null) {
                boolean pass = false;
                for (int i = 0; i < imagePixelSizeFilterArray.length; i++) {
                    if (width >= imagePixelSizeFilterArray[i][0] && height >= imagePixelSizeFilterArray[i][1]) {
                        pass = true;
                        break;
                    }
                }
                if (!pass) {
                    return false;
                }
            }
            if (file.length() < taskConfig.getImageMinSize()*1024) {
                return false;
            }
            return true;
        } catch (IOException e) {
            logger.error("读取文件异常", e);
        }
        return false;
    }

}
